<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css">


  <meta name="keywords" content="大数据,">





  <link rel="alternate" href="/atom.xml" title="King blog" type="application/atom+xml">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2">






<meta name="description" content="什么是Canal ​		Canal是用 Java开发的基于数据库增量日志解析，提供增量数据订阅 &amp;amp;消费的中间件。目前 。 Canal主要支持了 MySQL的 Binlog解析，解析完成后才利用 Canal Client来处理获得的相关数据。 （数据库同步需要阿里的 Otter中间件，基于 Canal）。">
<meta name="keywords" content="大数据">
<meta property="og:type" content="article">
<meta property="og:title" content="大数据之Canal">
<meta property="og:url" content="https://zhongxc.cc/6c278c39.html">
<meta property="og:site_name" content="King blog">
<meta property="og:description" content="什么是Canal ​		Canal是用 Java开发的基于数据库增量日志解析，提供增量数据订阅 &amp;amp;消费的中间件。目前 。 Canal主要支持了 MySQL的 Binlog解析，解析完成后才利用 Canal Client来处理获得的相关数据。 （数据库同步需要阿里的 Otter中间件，基于 Canal）。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2023-02-13T03:36:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="大数据之Canal">
<meta name="twitter:description" content="什么是Canal ​		Canal是用 Java开发的基于数据库增量日志解析，提供增量数据订阅 &amp;amp;消费的中间件。目前 。 Canal主要支持了 MySQL的 Binlog解析，解析完成后才利用 Canal Client来处理获得的相关数据。 （数据库同步需要阿里的 Otter中间件，基于 Canal）。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.2',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhongxc.cc/6c278c39.html">





  <title>大数据之Canal | King blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">King blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhongxc.cc/6c278c39.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="King">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/assets/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="King blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">大数据之Canal</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2023-02-13T11:36:33+08:00">
                2023-02-13
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2023-02-13T11:36:33+08:00">
                2023-02-13
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/大数据/" itemprop="url" rel="index">
                    <span itemprop="name">大数据</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="什么是canal">什么是Canal</h4>
<p>​		Canal是用 Java开发的基于数据库增量日志解析，提供增量数据订阅 &amp;消费的中间件。目前 。 Canal主要支持了 MySQL的 Binlog解析，解析完成后才利用 Canal Client来处理获得的相关数据。 （数据库同步需要阿里的 Otter中间件，基于 Canal）。</p>
<a id="more"></a>
<h4 id="什么是binlog">什么是Binlog</h4>
<p>​		MySQL的二进制日志可以说MySQL最重要的日志了，它记录了所有的DDL和DML（除了数据库查询）语句，以事件形式记录，还包含语句所执行的消耗时间，MySQL的二进制是事务安全性的。</p>
<p>​		一般来说，开启二进制日志大概会有1%的性能损耗，二进制有两个重要的使用场景</p>
<p>​		一、MySQL Replication在Master端开启Binlog，Master把它的二进制日志传递给Slaves来达到Master-Slave数据一致的目的。</p>
<p>​		二、自然就是数据恢复了，通过使用MySQL Binlog工具来使恢复数据</p>
<p>​		二进制日志包括两类文件，：二进制日志索引文件（文件名后缀为.index）用于记录所有的二进制文件，二进制日志文件（文件名后缀为.00000*）记录数据库所有的DDL和DML（除了数据库查询语句）语句事件。</p>
<h4 id="binlog的分类">Binlog的分类</h4>
<p>​		MySQL Binlog的格式有三种，分别是 STATEMENT,MIXED,ROW。在配置文件中可以选择配置 binlog_format= statement|mixed|row。 三种格式的 区别：</p>
<p>​		1）statement 语句级， binlog会记录每次一执行写操作的语句。相对 row模式节省空间，但是可能产生不一致性，比如 update tt set create_date= 如果用 binlog日志进行恢复，由于执行时间不同可能产生的数据就不同。
​			优点：节省空间 。
​			缺点：有可能造成数据不一致。</p>
<p>​		2 row 行级， binlog会记录每次操作后每行记录的变化。
​			优点：保持数据的绝对一致性。因为不管sql是什么，引用了什么函数，他只记录执行后的效果。
​			缺点：占用较大空间。</p>
<p>​		3）mixed statement的升级版，一定程度上解决了，因为一些情况而造成的 statement模式不一致问题 默认还是 statement 在某些情况下譬如：当函数中包含 UUID() 时；包含AUTO_INCREMENT 字段的表被更新时；执行 INSERT DELAYED 语句时；用 UDF 时；会按照ROW的方式进行处理
​			优点：节省空间，同时兼顾了一定的一致性。
​			缺点：还有些极个别情况依旧会造成不一致，另外statement和 mixed对于需要对binlog的监控的情况都不方便。
综合上面对比，
Canal想做监控分析，选择 row格式比较合适 。</p>
<h4 id="mysql主从复制过程">MySQL主从复制过程</h4>
<p>1）Master主库将改变记录，写到二进制日志 (Binary Log)中
2）Slave从库向 MySQL Master发送 dump协议，将 Master主库的 binary log events拷贝到它的中继日志 (relay log）
3）Slave从库读取并重做中继日志中的事件，将改变的数据同步到自己的数据库。</p>
<h4 id="canal的工作原理">Canal的工作原理</h4>
<p>很简单，就是把自己伪装成 Slave，假装从 Master复制数据 。</p>
<h4 id="mysql的准备">MySQL的准备</h4>
<h5 id="创建数据库">创建数据库</h5>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CREATE DATABASE mydb1;</span><br></pre></td></tr></table></figure>
<h5 id="创建数据库表">创建数据库表</h5>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE user_info(</span><br><span class="line">`id` VARCHAR(255),</span><br><span class="line">`name` VARCHAR(255),</span><br><span class="line">`sex` VARCHAR(255)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h5 id="修改-配置-文件-开启-binlog">修改 配置 文件 开启 Binlog</h5>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[root@server01 conf]$ vim /my_data/mysql05/conf/my.cnf</span><br><span class="line">server-id=1</span><br><span class="line">log-bin=mysql-bin</span><br><span class="line">binlog_format=row</span><br><span class="line">binlog-do-db=mydb1</span><br></pre></td></tr></table></figure>
<p>注意：binlog-do-db根据自己的情况进行修改，指定具体要同步的数据库 ，如果不配置则表示所有数据库均开启 Binlog</p>
<h5 id="重启mysql使配置生效">重启MySQL使配置生效</h5>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker restart mysql05</span><br></pre></td></tr></table></figure>
<h5 id="赋权限">赋权限</h5>
<p>在MySQL中执行</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; set global validate_password_length=4;</span><br><span class="line">mysql&gt; set global validate_password_policy=0;</span><br><span class="line">mysql&gt; GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO &apos;canal&apos;@&apos;%&apos; IDENTIFIED BY &apos;canal&apos;;</span><br></pre></td></tr></table></figure>
<h4 id="canal-的下载和安装">Canal 的下载和安装</h4>
<h5 id="下载并解压-jar包">下载并解压 Jar包</h5>
<p><a href="https://github.com/alibaba/canal/releases" target="_blank" rel="noopener">https://github.com/alibaba/canal/releases</a></p>
<p style="color:red">注意：canal解压后是分散的，我们在指定解压目录的时候需要将 canal指定上</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@server01 /]$ mkdir /opt/module/canal</span><br><span class="line">[root@server01 /]$ tar -zxvf canal.deployer-1.1.2.tar.gz -C /opt/module/canal</span><br></pre></td></tr></table></figure>
<h5 id="修改-canal-properties的配置">修改 canal.properties的配置</h5>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[root@server01 conf]$ pwd</span><br><span class="line">/opt/module/canal/conf</span><br><span class="line">[root@server01 conf]$ vim canal.properties</span><br><span class="line"><span class="meta">#</span><span class="bash"><span class="comment">######## common argument #############</span></span></span><br><span class="line">canal.id = 1</span><br><span class="line">canal.ip =</span><br><span class="line">canal.port = 11111</span><br><span class="line">canal.metrics.pull.port = 11112</span><br><span class="line">canal.zkServers =</span><br><span class="line"><span class="meta">#</span><span class="bash"> flush data to zk</span></span><br><span class="line">canal.zookeeper.flush.period = 1000</span><br><span class="line">canal.withoutNetty = false</span><br><span class="line"><span class="meta">#</span><span class="bash"> tcp, kafka, RocketMQ</span></span><br><span class="line">canal.serverMode = tcp</span><br><span class="line"><span class="meta">#</span><span class="bash"> flush meta cursor/parse position to file</span></span><br><span class="line">canal.instance.parser.parallel = false</span><br></pre></td></tr></table></figure>
<p>说明：这个文件是 canal的基本通用配置， canal端口号默认就是 11111 修改 canal的输出 model，默认 tcp，改为输出到 kafka
多实例配置如果创建多个实例 通过前面 canal架构，我们可以知道，一个 canal服务中可以有多个 instance conf/下的每一个 example即是一个实例，每个实例下面都有独立的配置文件。默认只有一个实例 example，如果需要多个实例处理不同的 MySQL数据的话，直接拷贝出多个 example，并对其重新命名，命名和配置文件中指定的名称一致，然后修改canal.properties中的 canal.destinations=实例 1，实例 2，实例 3。</p>
<h5 id="修改-instance-properties">修改 instance.properties</h5>
<p>我们这里只读取一个MySQL数据，所以只有一个实例，这个实例的配置文件在conf/example目录下</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[root@server01 example]$ pwd</span><br><span class="line">/opt/module/canal/conf/example</span><br><span class="line">[root@server01 example]$ vim instance.properties</span><br></pre></td></tr></table></figure>
<p>1）配置 MySQL服务器地址</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"><span class="comment"># mysql serverId , v1.0.26+ will autoGen</span></span></span><br><span class="line">canal.instance.mysql.slaveId=20</span><br><span class="line"><span class="meta">#</span><span class="bash"> <span class="built_in">enable</span> gtid use <span class="literal">true</span>/<span class="literal">false</span></span></span><br><span class="line">canal.instance.gtidon=false</span><br><span class="line"><span class="meta">#</span><span class="bash"> position info</span></span><br><span class="line">canal.instance.master.address=127.0.0.1:3306</span><br></pre></td></tr></table></figure>
<p>2）配置连接 MySQL的用户名和密码，默认就是我们前面授权的 canal</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> username/password</span></span><br><span class="line">canal.instance.dbUsername=canal</span><br><span class="line">canal.instance.dbPassword=canal</span><br><span class="line">canal.instance.connectionCharset=UTF8 </span><br><span class="line">canal.instance.defaultDatabaseName=test</span><br><span class="line"><span class="meta">#</span><span class="bash"> <span class="built_in">enable</span> druid Decrypt database password</span></span><br><span class="line">canal.instance.enableDruid=false</span><br></pre></td></tr></table></figure>
<h4 id="常见问题">常见问题</h4>
<ol>
<li>
<p>尝试多次，客户端一直读取不到binlog变更</p>
<p><a href="https://github.com/alibaba/canal/issues/1429" target="_blank" rel="noopener">https://github.com/alibaba/canal/issues/1429</a></p>
</li>
<li>
<p>Canal.deployer 启动报错说CHARACTER SET 'utf8' COLLATE 'utf8_unico', expect null</p>
<p>删除实体（默认example）里面的文件 h2.mv.db</p>
</li>
</ol>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wpay.png" alt="King 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="King 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    King
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zhongxc.cc/6c278c39.html" title="大数据之Canal">https://zhongxc.cc/6c278c39.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/大数据/" rel="tag"># 大数据</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/228116e7.html" rel="next" title="tp3 and or复合查询">
                <i class="fa fa-chevron-left"></i> tp3 and or复合查询
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image" src="/assets/images/avatar.jpg" alt="King">
          
            <p class="site-author-name" itemprop="name">King</p>
            <p class="site-description motion-element" itemprop="description"></p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">61</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">16</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">34</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crytostring" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:cqzhongxc@outlook.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://gitee.com/ikings" target="_blank" title="gitee">
                  
                    <i class="fa fa-fw fa-git"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.stephen520.cn" target="_blank" title="石鹏">
                  
                    <i class="fa fa-fw fa-scribd"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.tutorialspoint.com/index.htm" target="_blank" title="tutorialspoint">
                  
                    <i class="fa fa-fw fa-tumblr"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://leetcode-cn.com/interview" target="_blank" title="leetcode">
                  
                    <i class="fa fa-fw fa-code"></i></a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.geeksforgeeks.org/php-addcslashes-function" target="_blank" title="geeksforgeeks">
                  
                    <i class="fa fa-fw fa-diamond"></i></a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是canal"><span class="nav-number">1.</span> <span class="nav-text">什么是Canal</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是binlog"><span class="nav-number">2.</span> <span class="nav-text">什么是Binlog</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#binlog的分类"><span class="nav-number">3.</span> <span class="nav-text">Binlog的分类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#mysql主从复制过程"><span class="nav-number">4.</span> <span class="nav-text">MySQL主从复制过程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#canal的工作原理"><span class="nav-number">5.</span> <span class="nav-text">Canal的工作原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#mysql的准备"><span class="nav-number">6.</span> <span class="nav-text">MySQL的准备</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#创建数据库"><span class="nav-number">6.1.</span> <span class="nav-text">创建数据库</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#创建数据库表"><span class="nav-number">6.2.</span> <span class="nav-text">创建数据库表</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#修改-配置-文件-开启-binlog"><span class="nav-number">6.3.</span> <span class="nav-text">修改 配置 文件 开启 Binlog</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#重启mysql使配置生效"><span class="nav-number">6.4.</span> <span class="nav-text">重启MySQL使配置生效</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#赋权限"><span class="nav-number">6.5.</span> <span class="nav-text">赋权限</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#canal-的下载和安装"><span class="nav-number">7.</span> <span class="nav-text">Canal 的下载和安装</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#下载并解压-jar包"><span class="nav-number">7.1.</span> <span class="nav-text">下载并解压 Jar包</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#修改-canal-properties的配置"><span class="nav-number">7.2.</span> <span class="nav-text">修改 canal.properties的配置</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#修改-instance-properties"><span class="nav-number">7.3.</span> <span class="nav-text">修改 instance.properties</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#常见问题"><span class="nav-number">8.</span> <span class="nav-text">常见问题</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2020 &mdash; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-random"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">King</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动</div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">主题 &mdash; <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.2</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  

  






  




	





  








  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('3');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.2"></script>


</body>
</html>
